package com.liao.shapping.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.liao.shapping.R;
import com.liao.shapping.adapter.ItemShopListViewLayoutAdapter;
import com.liao.shapping.adapter.ItemShoppingcartListviewLayoutAdapter;
import com.liao.shapping.domain.InfoBean;
import com.liao.shapping.utils.ContentDatas;

import java.util.ArrayList;
import java.util.List;

public class ShoppingCartActivity extends AppCompatActivity implements View.OnClickListener, ItemShoppingcartListviewLayoutAdapter.CallBack {
    private ArrayList<Integer> list;
    private ImageView img_back;
    private TextView tv_title;
    private ListView listView;
    private TextView tv_sum;
    private Button btn_pay;
    private ArrayList<InfoBean> infoBeans;
    private int id;
    private ItemShoppingcartListviewLayoutAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_cart);
        getSupportActionBar().hide();
        Intent intent = getIntent();
        list = intent.getIntegerArrayListExtra("list");
        id = intent.getIntExtra("id", 0);
        initView();
    }


    private void initView() {
        tv_sum = (TextView) findViewById(R.id.tv_sum);
        btn_pay = (Button) findViewById(R.id.btn_pay);
        TextView tv_title = findViewById(R.id.tv_title);
        listView = findViewById(R.id.listView);
        tv_title.setText("购物车");

        btn_pay.setOnClickListener(this);
        findViewById(R.id.img_back).setOnClickListener(this);
        infoBeans = new ArrayList<>();
        List<InfoBean> infoBeans = ContentDatas.getAllList().get(id);
        for (Integer integer : list) {
            InfoBean infoBean = infoBeans.get(integer);
            this.infoBeans.add(infoBean);
        }
        adapter = new ItemShoppingcartListviewLayoutAdapter(this, this.infoBeans, this);
        listView.setAdapter(adapter);
        changeSumPrice();
    }

    private void changeSumPrice() {
        double sum = 0;
        for (int i = 0; i < infoBeans.size(); i++) {
            InfoBean infoBean = infoBeans.get(i);
            sum += infoBean.getPrice() * infoBean.getBuycount();
        }
        String s = "￥" + sum;
        tv_sum.setText(s);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_pay:
                startActivity(new Intent(this, ShoppingPayActivity.class));
                break;
            case R.id.img_back:
                onBackPressed();
                finish();
                break;
        }
    }

    @Override
    public void changeNum() {
        changeSumPrice();
    }
}
